package com.nhim.core;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class ReflectionHelper {

	public static Object createInstanceFrom(String className,
			String contructorParamValue) throws ClassNotFoundException,
			SecurityException, NoSuchMethodException, IllegalArgumentException,
			InstantiationException, IllegalAccessException,
			InvocationTargetException {
		
		Class<?> cls = Class.forName(className);
		Constructor<?> ct = cls.getConstructor(String.class);
		return ct.newInstance(contructorParamValue);

	}

	public static Object loadInstanceFromFile(String path, String className,
			String contructorParamValue) throws MalformedURLException,
			ClassNotFoundException, SecurityException, NoSuchMethodException,
			IllegalArgumentException, InstantiationException,
			IllegalAccessException, InvocationTargetException {
		
		File file = new File(path);
		// Convert File to a URL
		URL url = file.toURI().toURL();
		URL[] urls = new URL[] { url };

		// Create a new class loader with the directory
		ClassLoader loader = new URLClassLoader(urls);

		Class<?> cls = loader.loadClass(className);
		Constructor<?> ct = cls.getConstructor(String.class);
		return ct.newInstance(contructorParamValue);
	}

	public static Object loadInstanceFromJar(String path, String className,
			String contructorParamValue) throws MalformedURLException,
			ClassNotFoundException, SecurityException, NoSuchMethodException,
			IllegalArgumentException, InstantiationException,
			IllegalAccessException, InvocationTargetException {
		
		URL[] urls = { new URL("jar:file:" + path + "!/") };
		ClassLoader loader = URLClassLoader.newInstance(urls);
		Class<?> cls = loader.loadClass(className);
		Constructor<?> ct = cls.getConstructor(String.class);
		return ct.newInstance(contructorParamValue);

	}

}
